<template>
    <div v-if="nolimit">
        没有权限
    </div>
    <div v-else class="editCom-wrapper ui container segment">
        <i v-if="forModal" class="ui icon large close modal_close" @click="$emit('toHidden')"></i>
        <div class="ui very relaxed  grid">
            <div class="sixteen wide column">

                <form action="" class="ui form" :class='{notModalForm}' @submit.prevent="onPreSubmit">
                    <div class="ui header">{{titleType}}{{title}}</div>
                    <template v-if="group.length>1">
                        <div class="ui menu attached tabular top editcom">
                            <a href="javascript:;" class="item" :data-tab="'item_'+ind" :class="{active:ind==0}"
                               v-for="(g,ind) in group">{{g}}</a>
                        </div>
                        <div v-if="!loading" class="ui bottom attached tab segment" :class="{active:ind==0}"
                             :data-tab="'item_'+ind"
                             v-for="(fields,ind) in attrGroupField">
                            <div v-show="tab_title[ind]" class="ui message icon warning tiny">
                                <i class="icon warning"></i>
                                <span>{{tab_title[ind]}}</span>
                            </div>
                            <template v-if="fields.length>0" v-for="field in fields">
                                <myfields v-if="editType&&field&&!field.notShow" :param="{}" :field="field" :ctl="ctl"
                                          @setVo='toSetEditVo' :ref="field.name" :editType="editType"></myfields>
                            </template>

                        </div>
                    </template>

                    <template v-else>
                        <template v-if="!loading">
                            <span v-show="false">{{_fields = attrGroupField[0]}}</span>
                            <template v-if="_fields.length>0" v-for="field in _fields">
                                <myfields v-show="!notShows[field.name]" v-if="editType&&field&&!field.notShow"
                                          :param="{}"
                                          :field="field" :ctl="ctl"
                                          @setVo='toSetEditVo' :ref="field.name" :editType="editType"></myfields>
                            </template>
                        </template>
                    </template>


                    <p :class='{submitRow:!forModal&&!otherEdit}'>
                        <button v-if="onsubmit" class="ui loading button">Loading</button>
                        <button v-else type="submit" class="ui sub_btn button">提 交</button>
                        <!--<button  type="submit" class="ui button">提 交</button>-->

                    </p>


                </form>


            </div>
        </div>
        <loading :loading="loading"></loading>
    </div>

</template>

<script>
    import tool from 'src/util/tool';
    import util from '_util/index';
    import logic from '_logic';
    import model from '_model';
    import _valid from '_valid';

    import myfields from 'components/edit/fields';
    import loading from 'components/dimmer/loading';


    var in_array = require('in_array');

    import {
        mapState,
        mapMutations,
        mapGetters,
        mapActions
    }
        from 'vuex'

    export default {
        data() {
            return {
                type: 'add',
                edit_model: '',
                title: '',
                mid: 0,
                valids: null,
                interval: null,
                fields: null,
                hide_field_ids: [],
                showConf: [],
                field_type_conf: [],
                field_rel_conf: [],
                notShows: {},
                attrGroup: null,
                group: [],
                tab_title: [],
                nolimit: false,
                getConfed: false,
                onsubmit: false
            }
        },
        methods: {
            myinit(){
                util.store.push(this, 'setIsinEditModal', 'isinEditModal', false, Boolean(this.forModal), 'edit');
                util.store.push(this, 'setIsinOtherEdit', 'isinOtherEdit', false, Boolean(this.otherEdit), 'edit');
                this.setMid()
                this.setTitle()

            },
            set_edit_conf() {
                logic.edit.set_edit_conf(this);
            },
            toSetEditVo(name, val) {
                logic.edit.toSetEditVo(this, name, val);
                this.hl_field_change([name, val]);
                if (['Pattr', 'ProductType'].contains(this.ctl))
                    model.Pattr.for_show_type_change(this, name, val)
                else
                    util.modelFn(this.ctl,'for_show_type_change',this,name,val);
            },
            hl_field_change([fname, val]) {
                if (in_array(fname, this.judgeFields)) {
                    logic.edit.hl_showConf(this);
                }
                if (in_array(fname, this.typeCtlFields)) {
                    logic.edit.hl_field_type_conf(this, fname, val);
                }
                if (in_array(fname, this.relFields)) {
                    logic.edit.hl_field_rel_conf(this, fname, val);
                }
            },
            onPreSubmit() {
                logic.edit.onPreSubmit(this, _valid)

            },
            toSubmit(clb=null) {
                let op = this.$store.state.global.op || 'insert';
                this.$set(this.$data, 'onsubmit', true)


                //防止长时间转圈
                logic.edit.hl_submit_btn_load(this);


//                let ctl = this.$store.state.global.current_ctl;
                let ctl = this.edit_model;
                let pre = 'index'

//                if (in_array(ctl, this.$store.state.global.module_permission.changeApi)) {
//                    pre = 'user'
//
//                }
                logic.edit.beforeSubmit(this, ctl)

                let url = tool.getApi(this, ctl, op, pre);
                let state = logic.edit.get_vo_state(this);
                let vo = this.$store.state.global[state];

                util.getDataCom(this, url, vo, (rs) => {
                    util.showMsg(this, 'success', '操作成功！')
                    logic.edit.afterSubmit_success(this);
                    this.$set(this.$data, 'onsubmit', false);

                    let is_insert_hide = logic.edit.is_insert_hide(this);

                    let is_ok_jump=logic.edit.is_ok_jump(this)
                    let is_modal_edit=logic.edit.is_modal_edit(this)
                    let b = !is_modal_edit && is_ok_jump;

                    if(clb) {
                        clb(this,rs);
                    }

                    if(b) {
                        this.$router.push(`/page/list?ctl=${this.ctl}`);
                    }else if(is_insert_hide||!this.isAdd)
                        this.$emit("oncomplate");


                }, (data, msg) => {

                    this.$set(this.$data, 'onsubmit', false)


                    msg = data && data.length > 1 ? `${data.errmsg}(${data.debug})` : msg;

                    let option = {err_lvl: data.err_lvl};
                    util.http.SRMsg(this, msg, option, 1);
                });

            },
            getFields() {
                let url = tool.getApi(this, 'Editget', 'getFields');
                if (this.mid) {

                    let param = {
                        mid: this.mid,
                        isAdd: Number(this.isAdd)
                    }
                    model.Hproduct.forSpecialType(this, this.mid, param);
                    util.getDataCom(this, url, param, (rs) => {
                        this.fields = rs
                        util.store.commit(this,'set_editCom_fields', this.fields)
                        this.set_edit_conf()
                        this.getValidList()
                        logic.edit.hl_hide_type(this);
                    });

                }
            },
            toGetData() {
                if (this.forModal) {
                    if (this.modal_info) {
                        this.getFields()
                        this.getAttrGroup()
                    }
                } else {
                    this.getFields()
                    this.getAttrGroup()
                }
            },
            getAttrGroup() {
                let url = tool.getApi(this, 'Editget', 'getAttrGroup');
                // this.getModel();
                // let id = this.vuexRs
                let id = this.mid
                if (id) {
                    let param = {
                        id: id
                    }
                    util.getDataCom(this, url, param, (rs) => {
                        this.attrGroup = JSON.parse(rs.attr_group_str)
                        this.group = JSON.parse(rs.group_str)
                        if (rs.tab_title_str) {
                            this.tab_title = JSON.parse(rs.tab_title_str)
                        }
                    });

                }
            },
            getValidList() {
                let url = tool.getApi(this, 'Editget', 'getValidList');
                let mid = this.mid
                if (mid) {
                    let param = {
                        mid: mid
                    }
                    util.getDataCom(this, url, param, (data) => {
                        this.valids = data;
                        if (this.fields) {
                            this.fields.map(field => {
                                field.valid = data[field.name] || ''
                            })
                        }

                    });
                }
            },
            setMid(){
                let mid = 0
                if (this.modal_info) {
                    mid = this.modal_info.mid
                }
                else if (this.otherEdit) {
                    mid = this.otherEdit_mid;
                }
                else {
                    this.getModel();
                    mid = this.vuexRs
                }
                this.mid = mid;

            },
            setTitle() {
                if (this.forModal || this.otherEdit) {
                    this.getModelByMid(this.otherEdit ? this.otherEdit_mid : this.modal_info.mid);
                } else {
                    this.getModel(1);
                }
                let model = this.vuexRs;
                this.title = model.title;
                this.edit_model = model.name;

            },
            ...mapMutations('global',['getCtlByMid', 'getModel', 'getModelByMid']),

        },
        props: ['forModal', 'otherEdit','otherEdit_option', 'modal_edit', 'modal_info', 'otherEdit_mid'],
        computed: {
            _vo() {
                let voName = this.forModal ? 'editVoModal' : (this.otherEdit ? 'otherEditVo' : 'editVo');

                let vo = this.$store.state.global[voName];
                return vo;
            },
            notModalForm() {
                return !this.forModal && !this.otherEdit && !this.modal_edit;
            },
            judgeFields() {
                return this.showConf.map(obj => {
                    return obj.judge
                });
            },
            typeCtlFields() {
                return this.field_type_conf.map(obj => {
                    return obj.ctl_field
                });
            },
            relFields() {
                return this.field_rel_conf.map(obj => {
                    return obj.rel_field
                });
            },
            loading() {
                return !(this.attrGroupField && this.valids && this.getConfed);
            },
            editType() {
                let type = this.forModal ? 1 : (this.otherEdit ? 2 : 3);
                return `EditType_${type}`;
            },
            attrGroupField() {
                let tmp = []

                if (this.fields && this.attrGroup) {
                    let fields = util.hlField(this.fields)
                    this.attrGroup.forEach(group => {
                        let groupNew = group.map(id => {
                            return fields[id]
                        })
                        tmp.push(groupNew)
                    });
                }

                return tmp.length > 0 ? tmp : null
            },

            titleType() {
                if (this.forModal || this.otherEdit)
                    return '';
                else {
                    let rs = '';
                    let op = this.$store.state.global.op;
                    switch (op) {
                        case 'update':
                            rs = '更新';
                            break;
                        case 'insert':
                            rs = '添加';
                            break;
                        case 'copy':
                            rs = '复制';
                            break;
                    }
                    return rs;
                }
            },
            isAdd() {
                return util.getOp(this) == 'insert';
            },
            ctl() {
                return this.$route.query.ctl;
            },
            ...mapState('global',['vuexRs','editVoModal','editVo'])

        },
        components: {
            myfields,
            loading
        },
        created() {
            this.myinit()


            let eventVue = util.store.get(this,'eventVue');
            eventVue.$on('toSubmit', this.toSubmit)
            eventVue.$on('editCom_toSetEditVo', this.toSetEditVo)
//      eventVue.$on('hl_judge', this.hl_judge)

        },
        destroyed() {

            util.store.commit(this,'setSelectVals', {})

            let eventVue = util.store.get(this,'eventVue');
            eventVue.$off('toSubmit', this.toSubmit)
        },
        watch: {
            'modal_info.mid': function (val, old) {
                if (val != old) {
                    this.myinit();
                }
            },
            mid: function (val) {
                if (val) {
                    this.fields = null;
                    this.toGetData()
                }
            },
            showConf: function (val) {
                if (val) {
                    logic.edit.hl_showConf(this);
                }
            },
            ctl: function (val, old) {
                if (val != old) {
                    this.toGetData()
                }
            },
            loading: function (val, old) {
                if (!val) {
                    this.$nextTick(() => {
                        $('.menu.editcom>.item').tab({
                            history: false
                        });
//            if(this.forModal)
//              this.$emit('toClearInterval');
//            if(this.ctl=='Hproduct')
//              logic.Hproduct.toHide(this);
//            this.set_edit_conf();
                    })
                }
            }
        },
        mounted() {
            this.interval = window.setInterval(() => {
                if (!this.mid) {
                    this.myinit();
                } else {
                    window.clearInterval(this.interval)
                }
            }, 500);


        },
        updated() {
        }
    }
</script>

<style rel="stylesheet/less" scoped lang="less">

    @import "../../common/style/mixin";

    .fade-transition();
    .editCom-wrapper {
        position: relative;
        .ui.icon.close.modal_close {
            position: absolute;
            cursor: pointer;
            top: 10px;
            right: 10px;
            z-index: 100;
            color: rgba(0, 0, 0, 0.5);
            &:hover {
                color: rgba(0, 0, 0, 0.8);
            }
        }

        .submitRow {
            margin-top: 2em;
            .sub_btn {
                .sub_btn();
            };
        }
        .notModalForm {
            .submitBtn();
        }
        .ui.message.icon.warning.tiny {
            font-size: 0.57143em;
            display: flex;
        }
    }
</style>
